#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
from pathlib import Path
from datetime import datetime

# # Directory and file path
DIR_PATH = Path('..') / 'Core' / 'Inc'
FILE_PATH = DIR_PATH / 'version.h'


# Regex pattern to match FW_VERSION macro: V<major>.<minor>.<patch>
VERSION_PATTERN = re.compile(r'#define\s+FW_VERSION\s+"V(\d+)\.(\d+)\.(\d+)"')

def read_current_version(content: str):
    """
    Extract current version (major, minor, patch) from file content.
    Return None if not found.
    """
    m = VERSION_PATTERN.search(content)
    return tuple(map(int, m.groups())) if m else None

def bump_version(major: int, minor: int, patch: int):
    """
    Increment patch; if >15, reset patch and increment minor.
    """
    patch += 1
    if patch > 15:
        patch = 0
        minor += 1
    return major, minor, patch

def generate_header(major: int, minor: int, patch: int):
    """
    Generate the full content of version.h with version and build time.
    """
    version_str = f'V{major}.{minor}.{patch}'
    build_time = datetime.now().strftime('%Y%m%d%H%M%S')
    return (
        '// Auto-generated version header\n'
        '#ifndef FW_VERSION_H\n'
        '#define FW_VERSION_H\n\n'
        f'#define FW_VERSION   "{version_str}"\n'
        f'#define BUILD_TIME   "{build_time}"\n\n'
        '#endif // FW_VERSION_H\n'
    )

def ensure_version_header():
    # Ensure the directory exists
    DIR_PATH.mkdir(parents=True, exist_ok=True)

    # Determine version
    if FILE_PATH.exists():
        content = FILE_PATH.read_text(encoding='utf-8')
        current = read_current_version(content)
        if current:
            major, minor, patch = bump_version(*current)
            print(f'[ Gen version ] Detected existing version V{current[0]}.{current[1]}.{current[2]}, bumped to V{major}.{minor}.{patch}')
        else:
            print('[ Gen version ] No valid version macro found, initializing to V0.0.1')
            major, minor, patch = 0, 0, 1
    else:
        print('[ Gen version ] version.h not found, creating initial version V0.0.1')
        major, minor, patch = 0, 0, 1

    # Write out the new header
    FILE_PATH.write_text(generate_header(major, minor, patch), encoding='utf-8')
    print(f'[ Gen version ] {FILE_PATH} has been generated/updated with BUILD_TIME.')

if __name__ == '__main__':
    ensure_version_header()
